/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.system.sys.controller;

import cc.jweb.adai.web.system.sys.service.FileService;
import cc.jweb.boot.common.lang.Result;
import cc.jweb.boot.controller.JwebController;
import cc.jweb.boot.utils.file.FileTypeUtils;
import cc.jweb.boot.utils.file.FileUtils;
import cc.jweb.boot.utils.lang.ResponseUtils;
import cc.jweb.boot.utils.lang.StringUtils;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.Render;
import com.jfinal.upload.UploadFile;
import cc.jweb.adai.web.system.file.model.SysFile;
import io.jboot.web.controller.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RequestMapping(value = "/file", viewPath = "/WEB-INF/views/file")
public class FileController extends JwebController {


    /**
     * 文件上传接口
     */
    public void upload() throws IOException {
        UploadFile file = getFile();

        ;
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        String fileId = UUID.randomUUID().toString().replace("-", "");
        String fileSuffix = FileUtils.getFileSuffix(file.getFileName());
        String filePathName = yyyyMMdd.format(new Date()) + "/" + fileId + (StringUtils.isNotBlank(fileSuffix) ? "." + fileSuffix : "");
        // 将上传文件移到指定位置
        String filePath = FileService.service.getUploadPath() + filePathName;
        long fileSize = file.getFile().length();
        FileUtils.move(file.getFile().getAbsolutePath(), filePath);
        Result result = new Result(true);
        result.setMessage("上传成功！");
        SysFile sysFile = new SysFile();
        sysFile.setFileId(fileId);
        sysFile.setCreateDatetime(new Date());
        sysFile.setFilePath(filePathName);
        sysFile.setFileName(file.getFileName());
        sysFile.setFileSuffix(fileSuffix);
        sysFile.setFileType(FileTypeUtils.getFileType(fileSuffix).getValue());
        sysFile.setFileSize(fileSize);
        sysFile.save();
        Record record = sysFile.toRecord();
        record.set("file_url", "/file/download?fileId=" + sysFile.getFileId());
        result.setData(record);
        renderJson(result);
    }

    /**
     * 文件下载接口
     *
     * @throws IOException
     */
    public void download() throws IOException {
        Result result = new Result(false);
        String fileId = getPara("fileId");
        SysFile file = null;
        if (StringUtils.isNotBlank(fileId)) {
            file = SysFile.dao.findById(fileId);
        }
        if (file == null) {
            result.setSuccess(false).setMessage("找不到文件信息！");
            renderJson(result);
            return;
        }
        String fileName = FileService.service.getUploadPath() + file.getFilePath();
        File downFile = new File(fileName);
        if (!downFile.exists()) {
            renderJson(new Result(false, "找不到文件！"));
            return;
        }
        SysFile finalFile = file;
        render(new Render() {
            private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream;";
//            private static final String IMAGE_CONTENT_TYPE = "image/svg+xml;charset=UTF-8;";

            @Override
            public void render() {
                response.setHeader("Accept-Ranges", "bytes");
                //String newReportName  = reportName == null?"安全分析统计报告":reportName;
                String downloadFileNameHeader = ResponseUtils.getDownloadFileNameHeader(getRequest(), finalFile.getFileName());
                if ("svg".equalsIgnoreCase(finalFile.getFileSuffix())) {
                    response.setContentType("image/svg+xml;charset=UTF-8;");
                } else {
                    response.setHeader("Content-disposition", downloadFileNameHeader);
                }
                ServletOutputStream outputStream = null;
                InputStream fis = null;
                try {
                    outputStream = response.getOutputStream();
                    fis = new BufferedInputStream(new FileInputStream(downFile));
                    byte[] cache = new byte[1024];
                    int count = 0;
                    while ((count = fis.read(cache)) != -1) {
                        outputStream.write(cache, 0, count);//将缓冲区的数据输出到浏览器
                    }
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        });
    }

    /**
     * 获取文件信息
     */
    public void fileInfo() {
        Result result = new Result(false);
        String fileIds = getPara("fileIds");
        List<SysFile> files = new ArrayList<>();
        if (StringUtils.isNotBlank(fileIds)) {
            String[] fieldVs = fileIds.split(",");
            List<String> params = new ArrayList<>();
            String whereSql = "";
            for (String fieldV : fieldVs) {
                if (StringUtils.isNotBlank(fieldV)) {
                    whereSql += ",?";
                    params.add(fieldV);
                }
            }
            if (params.size() > 0) {
                files.addAll(SysFile.dao.find("select * from sys_file where file_id in (" + whereSql.substring(1) + ")", params.toArray()));
            }
        }
        if (files.size() <= 0) {
            result.setSuccess(false).setMessage("找不到文件信息！");
            renderJson(result);
            return;
        }
        result.setSuccess(true);
        result.setData(files);
        renderJson(result);
    }

}
